<template>
  <div class="app-container">
    <el-card class="box-card">
      <el-form :inline="true" :model="queryForm" class="query-form">
        <el-form-item label="综合查询">
          <el-input v-model.trim="queryForm.keywords" style="width: 180px;" clearable placeholder="请输入关键字" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="queryForm.status" placeholder="请选择状态" style="width: 180px;" clearable>
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" border stripe style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="字典名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="code" label="字典编码" min-width="180" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? 'success' : 'danger'">
              {{ scope.row.status == 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip />
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ $formatTimestamp(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="height: 18px;"></div>

      <el-pagination v-model:current-page="queryForm.pageNum" v-model:page-size="queryForm.pageSize"
        :page-sizes="[10, 50, 100, 500, 1000]" :total="total" layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 字典表单对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="750px" destroy-on-close>
      <el-form ref="formRef" :model="dictForm" :rules="dictRules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="字典名称" prop="name">
              <el-input v-model.trim="dictForm.name" placeholder="请输入字典名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字典编码" prop="code">
              <el-input v-model.trim="dictForm.code" placeholder="请输入字典类型" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="dictForm.status" placeholder="请选择状态">
                <el-option label="启用" :value="1" />
                <el-option label="禁用" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model.trim="dictForm.remark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数据" prop="items">
              <el-table ref="sortableRef" :data="items" border row-key="label" style="width: 100%">
                <el-table-column prop="label" label="数据标签">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.label" placeholder="请输入数据标签" />
                  </template>
                </el-table-column>
                <el-table-column prop="value" label="数据值">
                  <template #default="scope">
                    <el-input v-model.trim="scope.row.value" placeholder="请输入数据值" />
                  </template>
                </el-table-column>
                <el-table-column prop="color" label="颜色值" width="80">
                  <template #default="scope">
                    <el-color-picker v-model.trim="scope.row.color" />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="scope">
                    <el-button size="small" :icon="Rank" circle class="btn-drag"></el-button>
                    <el-button size="small" type="danger" :icon="Delete" circle
                      @click="items.splice(scope.$index, 1)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px;">
                <el-button type="primary" size="small"
                  @click="items.push({ label: '', value: '', color: '' })">添加数据</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { Rank, Delete } from '@element-plus/icons-vue'
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Sortable from 'sortablejs'
import { apiDictList, apiDictAdd, apiDictUpdate, apiDictDelete } from '@/api/system/dict'

//字典数据
const items = ref<Record<string, any>>([])

// 查询表单
const queryForm = ref<Record<string, any>>({
  pageNum: 1,
  pageSize: 10
})

// 列表与分页
const list = ref<any[]>([])
const total = ref(0)

// 获取列表
const fetchList = async () => {
  const res = await apiDictList(queryForm.value)
  list.value = res.data?.records || []
  total.value = res.data?.totalRow || 0
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 字典表单
const initDictForm = ref<Record<string, any>>({
  status: 1,
  items: []
})
const dictForm = ref<Record<string, any>>({ ...initDictForm.value })

// 表单验证规则
const dictRules = {
  name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入字典编码', trigger: 'blur' }]
}

// 表单引用
const formRef = ref()

// 查询
const handleQuery = () => {
  queryForm.value.pageNum = 1
  fetchList()
}

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增字典'
  isEdit.value = false
  // 重置表单
  items.value = []
  Object.assign(dictForm.value = {}, initDictForm.value)
  dialogVisible.value = true
  nextTick(() => {
    initRowSortable()
  })
}

// 编辑
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑字典'
  isEdit.value = true
  // 填充表单数据
  items.value = JSON.parse(row.items) || []
  Object.assign(dictForm.value, row)
  dialogVisible.value = true
  nextTick(() => {
    initRowSortable()
  })
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除【${row.name}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await apiDictDelete({ ids: String(row.id) })
    if (res.code == 200) {
      ElMessage.success('删除成功')
      handleQuery()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  })
}

// 提交表单
const submitForm = () => {
  formRef.value?.validate(async (valid: any) => {
    if (valid) {
      dictForm.value.items = JSON.stringify(items.value)
      let res: any;
      if (isEdit.value) {
        res = await apiDictUpdate(dictForm.value)
      } else {
        res = await apiDictAdd(dictForm.value)
      }
      if (res.code == 200) {
        ElMessage.success('保存成功')
        dialogVisible.value = false
        handleQuery()
      } else {
        ElMessage.error(res.message || '保存失败')
      }
    }
  })
}

// 分页相关
const handleSizeChange = (val: number) => {
  queryForm.value.pageSize = val
  queryForm.value.pageNum = 1
  fetchList()
}

const handleCurrentChange = (val: number) => {
  queryForm.value.pageNum = val
  fetchList()
}

// 表格拖动排序
const sortableRef = ref()
let rowSortableInstance: any = null

// 初始化行拖拽
const initRowSortable = () => {
  if (!sortableRef.value) return
  const tbody = sortableRef.value.$el.querySelector('.el-table__body-wrapper tbody')
  if (tbody) {
    if (rowSortableInstance) {
      rowSortableInstance.destroy()
    }
    rowSortableInstance = Sortable.create(tbody, {
      animation: 150,
      handle: '.btn-drag',
      ghostClass: 'row-ghost',
      chosenClass: 'row-chosen',
      dragClass: 'row-drag',
      onEnd: handleRowDragEnd,
    })
  }
}

// 行拖拽结束
const handleRowDragEnd = (evt: any) => {
  const { oldIndex, newIndex } = evt
  if (oldIndex != newIndex) {
    const movedItem = items.value.splice(oldIndex, 1)[0]
    items.value.splice(newIndex, 0, movedItem)
  }
}

// 初始化
onMounted(() => {
  fetchList()
})
</script>

<style scoped>
.app-container {
  padding: 0px;
}

.query-form {
  margin-bottom: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>